package badgegenerator.dao.mybatis;

import badgegenerator.dao.exceptions.MyBatisInitException;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisConnector {
    private static SqlSessionFactory sessionFactory = null;

    public static void configure() throws MyBatisInitException{
        String resource = "badgegenerator/dao/mybatis-config.xml";
        try{
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException ex) {
            throw new MyBatisInitException("Can't create session factory", ex);
        }
    }
    
    public static SqlSession getSession(boolean autoCommit) throws MyBatisInitException{
        if(sessionFactory != null)
            return sessionFactory.openSession(autoCommit);
        else
            throw new MyBatisInitException("MyBetisConnector is not configured. Call 'configure method first'");
    }
}
